import {
	defineStore
} from 'pinia'
import {
	WorkOrderMyIndexApi,
	WorkOrderReviewApi
} from '../../api/workOrder'
import {
	SubPages
} from '../../config/router-config'

import {
	queryParams
} from '../../utils/util'
import {
	useAuthStore
} from './auth'
import _ from 'lodash'
import {
	SystemApi
} from '../../api/system'


const userData = useAuthStore()

export const useHandleWorkOrder = defineStore('useHandleWorkOrder', {
	state: () => ({
		routerInfo: null,
		itemData: null,
		// 哪个模块进入
		whereModule: null,
		_mescroll: null,

	}),
	getters: {
		// 我的工单 			// 我的工单 处理人是我 
		myOrderButton() {
			return {
				/**
				 * 待派单
				 */
				"wait_delivery": [],

				/**
				 * 待接单
				 */
				"wait_accept": [this.AcceptOrderWorkOrder, this.ChargebackWorkOrder],

				/**
				 * 处理中
				 */
				"processing": [this.HandleWorkOrder],

				/**
				 * 已暂停
				 */
				"suspended": [this.OpenWorkOrder],
				/**
				 * 已终止
				 */
				"terminated": [this.RestartWorkOrder],
				/**
				 * 待审核
				 */
				"wait_audit": [this.Reject, this.Pass],
				/**
				 * 审核未通过
				 */
				"not_pass_audit": [this.HandleWorkOrder],
				/**
				 * 待评价
				 */
				"wait_appraisal": [this.EvaluateWorkOrder],
				/**
				 * 已结束
				 */
				"ended": [],
				/**
				 * 电话解决
				 */
				"end_phone": [],
				/**
				 * 工单升级
				 */
				"end_upgrade": [],
			}

		},
		// 工单查询
		orderSearchButton() {
			// 报修 我报修的或者我所在科室报修的
			return {
				/**
				 * 待派单
				 */
				"wait_delivery": [this.Reminder, this.TerminationWorkOrder],

				/**
				 * 待接单
				 */
				"wait_accept": [this.Reminder, this.TerminationWorkOrder],

				/**
				 * 处理中
				 */
				"processing": [this.Reminder, this.TerminationWorkOrder, ],

				/**
				 * 已暂停
				 */
				"suspended": [this.Reminder, this.TerminationWorkOrder],
				/**
				 * 已终止
				 */
				"terminated": [],
				/**
				 * 待审核
				 */
				"wait_audit": [],
				/**
				 * 审核未通过
				 */
				"not_pass_audit": [this.Reminder, this.TerminationWorkOrder],
				/**
				 * 待评价
				 */
				"wait_appraisal": [],
				/**
				 * 已结束
				 */
				"ended": [],
				/**
				 * 电话解决
				 */
				"end_phone": [],
				/**
				 * 工单升级
				 */
				"end_upgrade": [],
			}
		},

		// buttonState() {

		// 	return {

		// 	}
		// },
		ChargebackWorkOrder() {
			return {
				label: '退单',
				background: '#F2F3FF',
				color: '#0052D9',
				fnName: 'chargebackWorkOrder',
				tag: 'chargeback',

				where: {
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}

		},
		AcceptOrderWorkOrder() {
			return {
				label: '接单',
				buttonTheme: 'primary',
				fnName: 'acceptOrderWorkOrder',
				tag: '',

				where: {
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}
		},
		CompleteWorkOrder() {
			return {
				label: '完成工单',
				background: '#F2F3FF',
				color: '#0052D9',
				fnName: 'completeWorkOrder',
				tag: 'complete',

				where: {
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}
		},
		HandleWorkOrder() {
			return {
				label: '处理',
				buttonTheme: 'primary',
				fnName: 'handleWorkOrder',
				tag: 'handle',

				where: {
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}

		},
		// revokeWorkOrder() {
		// 	return {
		// 		label: '撤销',
		// 		background: '#F2F3FF',
		// 		color: '#0052D9',
		// 		fnName: 'revokeWorkOrder',
		// 		tag: '',
		// 	}

		// },
		EvaluateWorkOrder() {
			return {
				label: '立即评价',
				buttonTheme: 'primary',
				fnName: 'evaluateWorkOrder',
				tag: '',

				where: {
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}

		},
		TerminationWorkOrder() {
			return {
				label: '终止',
				background: '#F2F3FF',
				color: '#0052D9',
				fnName: 'terminationWorkOrder',
				tag: 'termination',
				// 报修科室 是登陆帐号所在科室
				handle: {
					user: null,
					// dept: userData.deptId,
					// createUser: userData.userId
				},
				where: {
					// 工单查询
					'orderSearch': {
						dept: userData.deptId,
						createUser: userData.userId
					},
					// 我的工单
					'myOrder': {

					}
				}
			}
		},
		OpenWorkOrder() {
			return {
				label: '开启',
				background: '#F2F3FF',
				color: '#0052D9',
				fnName: 'openWorkOrder',
				tag: '',

				where: {
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}
		},
		RestartWorkOrder() {
			return {
				label: '重启',
				background: '#F2F3FF',
				color: '#0052D9',
				fnName: 'restartWorkOrder',
				tag: '',
				where: {
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}

		},
		Reminder() {
			return {
				label: '催单',
				background: '#F2F3FF',
				color: '#0052D9',
				fnName: 'reminder',
				tag: '',

				where: {
					// 工单查询
					'orderSearch': {
						user: null,
						dept: userData.deptId,
						createUser: userData.userId
					},
					// 我的工单
					'myOrder': {
						user: null,
						dept: null,
						createUser: null
					}
				}

			}
		},
		Pass() {
			return {
				label: '通过',
				background: '#0052D9',
				color: '#fff',
				fnName: 'pass',
				tag: '',
				validate: false,

				where: {

					// 我的工单
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}
		},
		Reject() {
			return {
				label: '驳回',
				background: '#F2F3FF',
				color: '#0052D9',
				fnName: 'reject',
				tag: '',
				validate: false,
				where: {

					// 我的工单
					'myOrder': {
						user: userData.userId,
						dept: null,
					}
				}
			}
		},
	},
	actions: {

		resetUpScroll() {
			if (this._mescroll) {
				this._mescroll.resetUpScroll()
			}
		},
		setMescroll(v) {
			this._mescroll = v
		},
		setRouterInfo(data) {
			if (_.isEmpty(data)) {
				return
			}
			this.routerInfo = data
		},
		onCard(item, moduleName) {
			this.whereModule = moduleName
			const params = {
				orderNum: item.orderNum,
				orderState: item.currState,
				where: moduleName
			}
			uni.navigateTo({
				url: `${SubPages.WORK_ORDER_DETAIL.router}${queryParams(params)}`
			})

		},
		// 点击卡片上的按钮
		onButton(item, buttonItem, isDetailPage = false) {
			console.log(item, buttonItem);

			this[buttonItem.fnName](item, buttonItem.tag, isDetailPage)

		},
		// 驳回
		reject(item) {
			const d = item || this.itemData
			const params = {
				orderNum: d.orderNum,
			}
			uni.navigateTo({
				url: `${SubPages.WORK_ORDER_REVIEW_INDEX_REJECT.router}${queryParams(params)}`
			})
		},
		async pass(item, tag, isDetailPage = false) {
			const d = item || this.itemData
			const the = this
			const params = {
				orderNums: d.orderNum
			}
			try {
				await WorkOrderReviewApi.pass(params)
				uni.showToast({
					icon: 'success',
					title: '通过成功'
				})
				if (isDetailPage) {
					uni.navigateBack()
				} else {
					the.resetUpScroll()
				}
			} catch {
				uni.showToast({
					icon: 'error',
					title: err
				})
			}

		},

		/**
		 * 重启
		 */
		restartWorkOrder(item, tag, isDetailPage = false) {
			const d = item || this.itemData
			const the = this
			uni.showModal({
				content: '确认后，工单重启。工单将退回到“待派单”状态，需重新派单',
				title: '重启',
				success: async function() {
					try {
						await WorkOrderMyIndexApi.restart({
							orderNum: d.orderNum
						})
						if (isDetailPage) {
							uni.navigateBack()
						} else {
							the.resetUpScroll()
						}
					} catch (err) {
						console.log(err);
						uni.showToast({
							icon: 'error',
							title: err
						})
					}
				}
			})

		},
		/**
		 * 开启
		 */
		async openWorkOrder(item, tag, isDetailPage = false) {
			const d = item || this.itemData
			const the = this
			try {
				uni.showToast({
					icon: 'success',
					title: '开启成功'
				})
				await WorkOrderMyIndexApi.open({
					orderNum: d.orderNum
				})
				if (isDetailPage) {
					uni.navigateBack()
				} else {
					the.resetUpScroll()
				}
			} catch (err) {

			}


		},

		/**
		 * 终止
		 */
		terminationWorkOrder(data) {
			const d = data || this.itemData
			const params = {
				orderNum: d.orderNum,
				currState: d.currState,
				handleState: 'termination',
			}
			uni.navigateTo({
				url: `${SubPages.MY_WORK_ORDER_HANDLE.router}${queryParams(params)}`
			})
		},

		/**
		 * 评价
		 */
		evaluateWorkOrder(item) {
			const d = item || this.itemData
			const params = {
				orderNum: d.orderNum,
			}
			uni.navigateTo({
				url: `${SubPages.WORK_ORDER_EVA.router}${queryParams(params)}`
			})
		},
		/**
		 * 催单
		 */
		async reminder(item) {
			const d = item || this.itemData
			const params = {
				orderNum: d.orderNum,
			}
			try {
				const res = await WorkOrderMyIndexApi.reminder(params)
				uni.showModal({
					content: res.msg,
					title: '提示'
				})

			} catch (err) {
				console.error(err);
				uni.showToast({
					icon: 'error',
					title: err

				})
			}
		},

		/**
		 * 撤销
		 */
		revokeWorkOrder() {
			// 	this.setData({

			// 		dialogInfo: {
			// 			title: "撤销审核",
			// 			content: '确认后，工单撤回到“处理中”状态，可再次点击“完成”进入审核',
			// 			tag: 'revokeWorkOrder'
			// 		},
			// 		visible: true

			// 	})
		},

		/**
		 * 处理
		 */
		handleWorkOrder(item, handleState) {
			const d = item || this.itemData
			const params = {
				orderNum: d.orderNum,
				currState: d.currState,
				handleState: handleState || 'handle',
			}
			uni.navigateTo({
				url: `${SubPages.MY_WORK_ORDER_HANDLE.router}${queryParams(params)}`
			})

		},

		/**
		 *完成工单 
		 * @param {*} data 
		 */
		completeWorkOrder(item, handleState) {
			const d = item || this.itemData
			const params = {
				orderNum: d.orderNum,
				currState: d.currState,
				handleState: 'complete',
			}
			uni.navigateTo({
				url: `${SubPages.MY_WORK_ORDER_HANDLE.router}${queryParams(params)}`
			})
		},
		/**
		 * 退单
		 * @param {*} data 
		 */
		chargebackWorkOrder(item, handleState) {
			const d = item || this.itemData
			const params = {
				orderNum: d.orderNum,
				currState: d.currState,
				handleState: handleState || 'chargeback',
			}
			uni.navigateTo({
				url: `${SubPages.MY_WORK_ORDER_HANDLE.router}${queryParams(params)}`
			})
		},
		/**
		 * 接单
		 * @param {*} data 
		 */
		async acceptOrderWorkOrder(item, tag, isDetailPage = false) {
			const d = item || this.itemData
			const the = this
			try {
				const res = await SystemApi.getCurrentTeams()

				if (res.data?.length > 1) {
					const t = res.data
					uni.showActionSheet({
						itemList: _.map(t, 'teamName'),
						success: async function(res) {

							try {
								await WorkOrderMyIndexApi.acceptOrder({
									orderNum: d.orderNum,
									receiveTeam: t[res.tapIndex].id
								})
								uni.showToast({
									icon: 'success',
									title: '接单成功',
								})
								if (isDetailPage) {
									_.delay(() => {
										uni.navigateBack()
									}, 500)
								} else {
									the.resetUpScroll()
								}
							} catch (err) {
								uni.showToast({
									icon: 'error',
									title: err
								})
							}
						},

					})
				} else if (res.data?.length == 0) {
					try {
						await WorkOrderMyIndexApi.acceptOrder({
							orderNum: d.orderNum,
							receiveTeam: res.data[0].id
						})
						uni.showToast({
							icon: 'success',
							title: '接单成功',
						})
						if (isDetailPage) {
							_.delay(() => {
								uni.navigateBack()
							}, 500)
						} else {
							the.resetUpScroll()
						}
					} catch (err) {
						uni.showToast({
							icon: 'error',
							title: err
						})
					}

				} else {
					await WorkOrderMyIndexApi.acceptOrder({
						orderNum: d.orderNum,
					})
					uni.showToast({
						icon: 'success',
						title: '接单成功',
					})
					if (isDetailPage) {
						_.delay(() => {
							uni.navigateBack()
						}, 500)
					} else {
						the.resetUpScroll()
					}
				}






			} catch (err) {
				console.error(err);
				uni.showToast({
					icon: 'error',
					title: '出现错误',
				})
			}

		},
	},
	persist: {
		paths: ['itemData', 'routerInfo']
	},
})